<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="归属校区" prop="campusId">
        <treeselect style="width:200px" v-model="queryParams.campusId" :options="campusOptions" 
                :multiple="false" :disableBranchNodes="true"
                :show-count="true" placeholder="请选择归属校区" />
      </el-form-item>
      <el-form-item label="班级编号" prop="classCode">
        <el-input
          v-model="queryParams.classCode"
          placeholder="请输入班级编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <div v-if="highQueryFlag">
      <el-form-item label="科别" prop="subjectType">
        <el-select v-model="queryParams.subjectType" placeholder="请选择科别" clearable size="small">
          <el-option
                  v-for="dict in subjectTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级类别" prop="classType">
        <el-select v-model="queryParams.classType" placeholder="请类别" clearable size="small">
          <el-option
                v-for="dict in classTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="归属年级" prop="grade">
        <el-date-picker
                    v-model="queryParams.grade"
                    type="year"
                    value-format="yyyy"
                    placeholder="选择归属年级">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="行课学期" prop="classTerm">
        <el-select v-model="queryParams.classTerm" placeholder="请选择行课学期" clearable size="small">
          <el-option
                  v-for="dict in classTermOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="行课时间" prop="classBeginDate">
        <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
      </el-form-item>
      <el-form-item label="班主任" prop="masterUserId">
        <el-select
              v-model="queryParams.masterUserId"
              placeholder="请输入班主任"
              clearable
              size="small"
              style="width: 200px"
            >
              <el-option
                v-for="user in masterUserOptions"
                :key="user.userId"
                :label="user.nickName"
                :value="user.userId"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      </div>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="highQueryIcon" size="mini" @click="highQuery">高级查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:classInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          :disabled="single"
          @click="handleAddCopy"
          v-hasPermi="['edu:classInfo:add']"
        >复制&新建</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          :disabled="multiple"
          @click="handleSelectStatus"
          v-hasPermi="['edu:classInfo:add']"
        >应用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleSchedule"
          v-hasPermi="['edu:classInfo:edit']"
        >自动排课</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:classInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:classInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:classInfo:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
      :element-loading-text="loadingText" :data="classInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="班级ID" align="center" prop="classId" />-->
      <el-table-column label="归属校区" align="center" prop="campusName" width="180" />
      <el-table-column label="班级编号" align="center" prop="classCode" width="100" />
      <el-table-column label="班级名称" align="center" prop="className" width="180" />
      <el-table-column label="科别" :formatter="subjectTypeFormat" align="center" prop="subjectType" width="100" />
      <el-table-column label="班级类别" :formatter="classTypeFormat" align="center" prop="classType"  width="100"/>
      <el-table-column label="开课科数" align="center" prop="subjectNum" width="100" />
      <el-table-column label="开课总天数" align="center" prop="subjectDays" width="100" />
      <el-table-column label="归属年级" align="center" prop="grade" width="100" />
      <el-table-column label="行课学期" :formatter="classTermFormat" align="center" prop="classTerm" width="100" />
      <el-table-column label="行课开始时间" align="center" prop="classBeginDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.classBeginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="行课结束时间" align="center" prop="classEndDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.classEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班主任" align="center" prop="masterUserName" width="100" />
      <el-table-column label="状态" :formatter="statusFormat" align="center" prop="status" width="100" />
      <el-table-column label="操作" fixed="right" min-width="240px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:classInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleManulSchedule(scope.row)"
            v-hasPermi="['edu:classInfo:edit']"
          >手动排课</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['edu:classInfo:edit']"
          ><!--<router-link :to="'/' + scope.row.classId" class="link-type">-->
            <span>学生</span>
          <!--</router-link>--></el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:classInfo:remove']"
          >删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleCancel(scope.row)"
            v-hasPermi="['edu:classInfo:remove']"
          >撤销</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级信息对话框 -->
    <el-dialog :title="title" v-if="open" :visible.sync="open" width="1000px" >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeName" @tab-click="handleTabChange">
          <el-tab-pane label="基本信息" name="first">
            <el-row>
              <el-col :span="12">
                <el-form-item label="归属校区" prop="campusId">
                  <treeselect style="width:200px" v-model="form.campusId" :options="campusOptions" 
                        :multiple="false" :disableBranchNodes="true"
                        :show-count="true" placeholder="请选择归属校区" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="班级编号" prop="classCode">
                  <el-input v-model="form.classCode" placeholder="请输入班级编号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="班级名称" prop="className">
                  <el-input v-model="form.className" placeholder="请输入班级名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="科别" prop="subjectType">
                  <el-select v-model="form.subjectType" placeholder="请选择科别" clearable size="small">
                  <el-option
                          v-for="dict in subjectTypeOptions"
                          :key="dict.dictValue"
                          :label="dict.dictLabel"
                          :value="dict.dictValue"
                        ></el-option>
                </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="班级类别" prop="classType">
                  <el-select v-model="form.classType" placeholder="请类别">
                    <el-option
                        v-for="dict in classTypeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="班级开课科数" prop="subjectNum">
                  <el-input v-model="form.subjectNum" disabled placeholder="请输入班级开课科数" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="班级开课总天数" prop="subjectDays">
                  <el-input v-model="form.subjectDays" disabled placeholder="请输入班级开课总天数"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="归属年级" prop="grade">
                  <el-date-picker
                    v-model="form.grade"
                    type="year"
                    value-format="yyyy"
                    placeholder="选择归属年级">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="行课学期" prop="classTerm">
                  <el-select v-model="form.classTerm" placeholder="请选择行课学期" clearable size="small">
                    <el-option
                            v-for="dict in classTermOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                          ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="班主任" prop="masterUserId">
                  <el-select
                      v-model="form.masterUserId"
                      placeholder="请输入班主任"
                      clearable
                      size="small"
                      style="width: 200px"
                    >
                      <el-option
                        v-for="user in masterUserOptionsForm"
                        :key="user.userId"
                        :label="user.nickName"
                        :value="user.userId"
                      />
                    </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="行课开始时间" prop="classBeginDate">
                  <el-date-picker clearable size="small" style="width: 200px"
                    v-model="form.classBeginDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择行课开始时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行课结束时间" prop="classEndDate">
                  <el-date-picker clearable size="small" style="width: 200px"
                    v-model="form.classEndDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择行课结束时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-radio-group v-model="form.status">
                    <el-radio
                              v-for="dict in statusOptions"
                              :key="dict.dictValue"
                              :label="dict.dictValue"
                            >{{dict.dictLabel}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">

              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="上课时间" name="seventh">
            <week-time-select v-model="currentClassTime" :data="currentClassTime" @return-data="getReturnData" />
          </el-tab-pane>
          <el-tab-pane label="可选班型" name="second">
            <el-checkbox :indeterminate="isIndeterminateClassModel" v-model="checkClassModelAll" @change="handleClassModelCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedClassModel" @change="handleClassModelChange">
              <el-checkbox v-for="model in modelOptions" :label="model.modelId" :key="model.modelId">{{model.modelName}}</el-checkbox>
            </el-checkbox-group>
          </el-tab-pane>
          <el-tab-pane label="可选年级" name="third">
             <div class="block">
               <el-row>
                 <el-col :span="2">
                   <span class="demonstration">年级</span>
                 </el-col>
                 <el-col :span="gradeLength">
                   <el-tag
                    :key="tag"
                    v-for="tag in gradeOptions"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{tag}}
                  </el-tag>
                 </el-col>
                 <el-col :span="1">
                   <el-date-picker
                    v-model="gradeOption"
                    @change="checkGrades"
                    type="year"
                    value-format="yyyy"
                    placeholder="选择年级">
                  </el-date-picker>
                 </el-col>
               </el-row>
            </div>
          </el-tab-pane>
          <el-tab-pane label="可选校区" name="fourth">
            <el-row>
                 <el-col :span="1">
                   <span class="demonstration">校区</span>
                 </el-col>
                 <el-col :span="12">
                  <el-form-item label=""  style="width:600px;height:300px;">
                    <treeselect v-model="checkCampusIds"
                      :options="campusOptions" 
                      :multiple="true"
                      :disableBranchNodes="true"
                      :show-count="true" placeholder="请选择可选校区" />
                  </el-form-item>
                 </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="科目信息" name="fivth" style="height:500px">
            <el-button size="mini" type="primary"
              icon="el-icon-plus" @click="addClassSubjects">新增科目</el-button>
            <div style="margin: 15px 0;"></div>
            <el-row  style="margin-left: -115px;" v-for="(item,index) in classSubjects" :key="index">
                 <el-col :span="3">
                  <el-form-item label="">
                    <el-select style="width:120px" 
                      v-model="item.subjectId" 
                      @change="getTeachPlans(item.subjectId, item)" 
                      placeholder="请选择科目">
                      <el-option
                          v-for="subject in subjectOptions"
                          :key="subject.subjectId"
                          :label="subject.subjectName"
                          :value="subject.subjectId"
                        />
                    </el-select>
                  </el-form-item>
                 </el-col>
                 <el-col :span="5">
                  <el-form-item label="" prop="teacherDeptId">
                    <treeselect style="width:220px" v-model="item.teacherDeptId" :options="teacherDeptOptions" 
                            :multiple="false" :disableBranchNodes="true"
                            @select="selectQueryTeacher"
                            :show-count="true" placeholder="请选择教学组" />
                  </el-form-item>
                 </el-col>
                 <el-col :span="3">
                  <el-form-item label="">
                    <el-select
                          v-model="item.teachUserId"
                          placeholder="请选择教师"
                          clearable
                          size="small"
                          style="width: 120px"
                        >
                          <el-option
                            v-for="user in teacherUserOptions"
                            :key="user.userId"
                            :label="user.nickName"
                            :value="user.userId"
                          />
                        </el-select>
                  </el-form-item>
                 </el-col>
                 <el-col :span="3">
                  <el-form-item label="">
                    <el-select
                          v-model="item.teachPlanId"
                          placeholder="请选择教学计划"
                          clearable
                          size="small"
                          style="width: 120px"
                        >
                          <el-option
                            v-for="plan in teachPlanOptions"
                            :key="plan.teachPlanId"
                            :label="plan.teachPlanName"
                            :value="plan.teachPlanId"
                          />
                    </el-select>
                  </el-form-item>
                 </el-col>
                 <el-col :span="5">
                  <el-form-item label="">
                    <el-select
                          v-model="item.roomId"
                          placeholder="请选择教室"
                          clearable
                          size="small"
                          style="width: 150px"
                          @change="checkRooms(item.roomId, item)"
                        >
                          <el-option
                            v-for="room in roomOptions"
                            :key="room.roomId"
                            :label="room.roomName"
                            :value="room.roomId"
                          >
                            <span style="float: left">{{ room.roomName }}</span>
                            <span style="float: center; color: #8492a6; font-size: 13px">||{{ room.seatNum}}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">||{{ room.roomAddr }}</span>
                          </el-option>
                        </el-select>
                  </el-form-item>
                 </el-col>
                 <el-col :span="4">
                   <div style="text-align:center;">
                    <el-button size="mini" type="danger"
                      icon="el-icon-delete" v-if="classSubjects.length > 1" 
                      @click="delClassSubjects(index)">删除</el-button>
                   </div>
                 </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="排课规则" name="sixth">
            <el-checkbox-group v-model="scheduleRoleIds">
              <el-checkbox style="margin-top: 10px" v-for="dict in classScheduleRolesOptions" :label="dict.dictValue" :key="dict.dictValue">{{dict.dictLabel}}</el-checkbox>
            </el-checkbox-group>
            <div style="margin-top: 40px">
              <el-row>
                <el-col>
                  <span>连编排指同一天只排一门课，按天交叉排课。</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <span>自习规则指班级晚上不排课，由学生自习。</span>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" type="primary" @click="submitHoldForm">保 存</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="手动排课" v-if="manulScheduleOpen" :visible.sync="manulScheduleOpen" width="1000px" >
      <div class="box-right">
        <FullCalendar
          ref="fullCalendar"
          :button-text="buttonText"
          :header="{
            left: 'listDay,timeGridWeek,dayGridMonth, today',
            center: 'prevYear,prev, title, next,nextYear',
            right: ''
          }"
          :plugins="calendarPlugins"
          :weekends="calendarWeekends"
          :first-day="firstDay"
          :event-time-format="evnetTime"
          :all-day-slot="true"
          :event-limit="true"
          :events="calendarEvents"
          :event-limit-text="eventLimiTtext"
          :now-indicator="true"
          :display-event-end="false"
          :slot-label-format="{ // 周，日视图时，左侧的显示的时间格式，以下为：00:00，00:30...5:30
            hour: 'numeric',
            minute: '2-digit',
            omitZeroMinute: false,
            meridiem: 'short',
            hour12: false
          }"
          :column-format="{day: 'dddd M/d'}"
          :list-day-format="listDayFormat"
          all-day-text="全天"
          no-events-message="暂无日程"
          locale="zh-cn"
          class="calendar-main"
          week-number-calculation="ISO"
          default-view="dayGridMonth"
          @eventClick="eventClick"
          @datesRender="datesRender"
          @dateClick="handleDateClick"
        />
      </div>
    </el-dialog>

    <!-- 班级状态信息对话框 -->
    <el-dialog :title="title" :visible.sync="selectStatusOpen" width="600px" append-to-body>
      <el-form ref="selectStatusForm" :model="selectStatusForm" label-width="120px">
        <el-form-item label="开班状态" prop="classStatus">
          <el-select
                v-model="selectStatusForm.classStatus"
                placeholder="请选开班状态"
                clearable
                size="small"
                style="width: 200px"
              >
                <el-option
                  v-for="info in classStatusOptions"
                  :key="info.dictValue"
                  :label="info.dictLabel"
                  :value="info.dictValue"
                />
              </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitClassStatus">确 定</el-button>
        <el-button size="mini" @click="cancelClassStatus">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClassInfo, getClassInfo, delClassInfo, addClassInfo, updateClassInfo, exportClassInfo, cancelClassInfo, changeClassStatus } from "@/api/edu/classInfo";
import { treeselectByType } from "@/api/system/dept";
import { getSubjectsAll } from "@/api/edu/subjects";
import { listAllUserByDeptId, listUserByByIds } from "@/api/system/user";
import { listAllTeachPlan, listTeachPlanByIds } from "@/api/edu/teachPlan";
import { listAllClassModel } from "@/api/edu/classModel";
import { listAllRooms } from "@/api/edu/rooms";
import { handleAutoSchedule } from "@/api/edu/schedule";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {isDigits, checkDigits} from '@/utils/validate'
import weekTimeSelect from "@/components/weekTimeSelect"
import { unique } from '@/utils'

import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import timelinePlugin from '@fullcalendar/timeline'
import listPlugin from '@fullcalendar/list'
import '@fullcalendar/core/main.css'
import '@fullcalendar/daygrid/main.css'
import '@fullcalendar/timegrid/main.css'
import '@fullcalendar/list/main.css'
import calendarColor from '@/views/components/calendarColor.js'

export default {
  name: "ClassInfo",
  components: { Treeselect, weekTimeSelect, FullCalendar },
  data() {
    return {
      // 遮罩层
      loading: true,
      loadingText: '',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级信息表格数据
      classInfoList: [],
      campusOptions: [],
      roomOptions: [],
      statusOptions: [],
      subjectOptions: [],
      teacherUserOptions: [],
      subjectTypeOptions: [],
      classTypeOptions: [],
      modelOptions: [],
      masterUserOptions: [],
      masterUserOptionsForm: [],
      classScheduleRolesOptions: [],
      teachPlanOptions: [],
      currentClassTime: [], // 选择班级设置当前上课时间
      classTermOptions: [],
      activeName: 'first',
      // 高级查询图标
      highQueryIcon: 'el-icon-arrow-down',
      // 高级查询标志
      highQueryFlag: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示选择状态弹出层
      selectStatusOpen: false,
      classStatusOptions: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        campusId: null,
        classCode: null,
        className: null,
        subjectType: null,
        classType: null,
        subjectNum: null,
        subjectDays: null,
        grade: null,
        classTerm: null,
        classBeginDate: null,
        classEndDate: null,
        masterUserId: null,
        status: null,
      },
      // 表单参数
      form: {},
      selectStatusForm :{},
      // 表单校验
      rules: {
        campusId: [
          { required: true, message: "校区不能为空", trigger: "blur" }
        ],
        grade: [
          { required: true, message: "年级不能为空", trigger: "blur" }
        ],
        masterUserId: [
          { required: true, message: "班主任不能为空", trigger: "blur" }
        ],
      },
      validateDigits: (rule, value, callback) => {
        isDigits(rule, value, callback)
      },
      //------------------------------
      checkClassModelAll: false,
      checkedClassModel: [],
      isIndeterminateClassModel: false,
      //-------------------------------\
      gradeOption: '',
      gradeOptions: [],
      gradeLength: 2,
      //------------------------------
      checkCampusIds: [],
      //--------------------------------
      classSubjects: [
        {
          subjectId: null,
          teacherDeptId: null, // 没有实际用途，只是关联选教师
          teachUserId: null,
          teachPlanId: null,
          roomId: null
        }
      ],
      teacherDeptOptions: [],
      //teacherDeptId: null,
      //---------------------------
      scheduleRoleIds: [],
      // --------- 手动排课
      manulScheduleOpen: false,
      // 你需要用到的插件
      calendarPlugins: [
        // plugins must be defined in the JS
        dayGridPlugin,
        timeGridPlugin,
        timelinePlugin,
        listPlugin,
        interactionPlugin // needed for dateClick
      ],
      // 是否展示周六周日
      calendarWeekends: true,
      // 默认选中当天
      calendarEvents: [],
      // 存储所有事件，方便筛选
      calendarList: [],
      colorList: calendarColor.colorList,
      // 按钮文字
      buttonText: {
        month: '月',
        week: '周',
        day: '日',
        today: '今天'
      },
      evnetTime: {
        hour: 'numeric',
        minute: '2-digit',
        hour12: false
      },
      firstDay: 1, // 把每周设置为从周一开始
      scheduleLoading: false,
      calendarArr: [],
      // 首次选中不进行跳转日列表操作
      isFirstToDay: true,
      // 视图当前所展示的时间： 保证月，年切换时，视图更新引起的报错
      currentTime: '',
      // 储存当前活动的时间，保证月份切换时，小日历跟随切换
      currentActiveTime: '',
      // 储存显示日期的开始时间和结束时间
      activeTime: {},
      // 今日显示的联系
      todaySchedule: [],
    };
  },
  created() {
    
    this.queryCampus();
    this.queryTeacherDept();
    this.getClassModel();
    this.getSubjects();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("edu_subject_type").then(response => {
      this.subjectTypeOptions = response.data;
    });
    this.getDicts("edu_class_type").then(response => {
      this.classTypeOptions = response.data;
    });
    this.getDicts("edu_class_schedule_roles").then(response => {
      this.classScheduleRolesOptions = response.data;
    });
    this.getDicts("edu_class_term").then(response => {
      this.classTermOptions = response.data;
    });
    this.getDicts("edu_class_status").then(response => {
      this.classStatusOptions = response.data;
      // console.log(JSON.stringify(this.classStatusOptions))
    });
    this.getList();
  },
  watch: {
    'queryParams.campusId': 'selectQueryForm',
    'form.campusId': 'selectCampusForAll',
  },
  methods: {
    selectCampusForAll() {
      this.queryRoomAsync()
      this.selectForm()
    },
    queryCampus() {
      // 查询校区（deptType = 1）
      treeselectByType("1").then(response => {
        this.campusOptions = response.data;
      })
    },
    queryTeacherDept() {
      // 查询教学组（deptType = 4）
      treeselectByType("4").then(response => {
        this.teacherDeptOptions = response.data;
      })
    },
    getClassModel() {
      listAllClassModel().then(response => {
        this.modelOptions = response.data
      })
    },
    getSubjects() {
      getSubjectsAll().then(response => {
        this.subjectOptions = response.data
      })
    },
    getTeachPlans(value, item) {
      let subjectIds = []
      this.classSubjects.forEach(subject => {
        subjectIds.push(subject.subjectId)
      })

      if(unique(subjectIds)) {
        item.subjectId = null
        this.$message({
            type: 'warning',
            message: '科目不能重复，请修改'
          })
          return
      }

      let params = {
        subjectId: value,
        status: '0',
      }
      listAllTeachPlan(params).then(response => {
        this.teachPlanOptions = JSON.parse(JSON.stringify(response.data))
      })
    },
    checkRooms(value, item) {
      /*
      let roomIds = []
      this.classSubjects.forEach(subject => {
        roomIds.push(subject.roomId)
      })

      if(unique(roomIds)) {
        item.roomId = null
        this.$message({
            type: 'warning',
            message: '教室不能重复，请修改'
          })
          return
      }
      */
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    subjectTypeFormat(row, column) {
      return this.selectDictLabel(this.subjectTypeOptions, row.subjectType);
    },
    classTypeFormat(row, column) {
      return this.selectDictLabel(this.classTypeOptions, row.classType);
    },
    classTermFormat(row, column) {
      return this.selectDictLabel(this.classTermOptions, row.classTerm)
    },
    selectQueryForm() {
      if(this.queryParams.campusId === undefined || this.queryParams.campusId === null) {
        this.$message({
            type: 'warning',
            message: '请选择校区'
          })
          return
      }
      //console.log(this.queryParams.campusId)
      listAllUserByDeptId(this.queryParams.campusId).then(response => {
        this.masterUserOptions = []
        response.data.filter(data => {
          if(data.userName !== 'admin') {
            this.masterUserOptions.push(data)
          }
        })
      })
    },
    selectForm() {
      if(this.form.campusId === undefined || this.form.campusId === null) {
        this.$message({
            type: 'warning',
            message: '请选择校区'
          })
          return
      }
      listAllUserByDeptId(this.form.campusId).then(response => {
        this.masterUserOptionsForm = []
        response.data.filter(data => {
          if(data.userName !== 'admin') {
            this.masterUserOptionsForm.push(data)
          }
        })
      })
    },
    selectQueryTeacher(node) {
      if(node.id === undefined || node.id === null) {
        this.$message({
            type: 'warning',
            message: '请选择教学组'
          })
          return
      }
      listAllUserByDeptId(node.id).then(response => {
        this.teacherUserOptions = JSON.parse(JSON.stringify(response.data))
      })
    },
    /** 查询班级信息列表 */
    getList() {
      this.loading = true;
      listClassInfo(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.classInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    highQuery() {
      this.highQueryFlag = !this.highQueryFlag
      if(this.highQueryIcon === 'el-icon-arrow-down' ) {
        this.highQueryIcon = 'el-icon-arrow-up'
        
      } else {
        this.highQueryIcon = 'el-icon-arrow-down'
        let campusId = this.queryParams.campusId
        let classCode = this.queryParams.classCode
        let className = this.queryParams.className
        // 隐藏查询条件不展示
        this.dateRange = [];
        this.resetForm("queryForm");
        this.queryParams.campusId = campusId
        this.queryParams.classCode = classCode
        this.queryParams.className = className
      }
    },
    // 表单重置
    reset() {
      this.checkedClassModel = []
      this.gradeOptions = []
      this.checkCampusIds = []
      this.classSubjects = [
        {
          subjectId: null,
          teachUserId: null,
          teachPlanId: null,
          roomId: null
        }
      ],
      this.scheduleRoleIds = [],
      this.currentClassTime = []

      this.form = {
        classId: null,
        campusId: null,
        campusName: null,
        classCode: null,
        className: null,
        subjectType: null,
        classType: null,
        subjectNum: null,
        subjectDays: null,
        grade: null,
        classTerm: null,
        classBeginDate: null,
        classEndDate: null,
        masterUserId: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        eduClassGradeList: null,
        eduClassClassModelList: null,
        eduClassCampusList: null,
        eduClassSubjectsList: null,
        eduClassScheduleRolesList: null,
        eduClassTimeList: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.classId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级信息";
    },
    /** 应用按钮操作 */
    handleSelectStatus() {
      this.reset();
      this.selectStatusOpen = true;
      this.title = "选择班级状态信息";
    },
    /** 一键复制 */
    handleAddCopy(row) {
      this.activeName = "first"
      this.reset();
      const classId = row.classId || this.ids
      getClassInfo(classId).then(response => {
        this.form = response.data;
        this.form.classId = null // 复制新增，将ID号去掉, 子集不用去掉，先删后插的方式封装完之后就没有classId

        // 设置班级上课时间
        if(this.form.eduClassTimeList && null !== this.form.eduClassTimeList) {
          let times = []
          this.form.eduClassTimeList.forEach(data => {
            times.push({weekDay: data.weekDay, scheduleSegment: data.scheduleSegment})
          })
          this.currentClassTime = JSON.parse(JSON.stringify(times))
          this.form.eduClassTimeList = JSON.parse(JSON.stringify(times)) // 重新初始化对象，避免直接保存ID冲突
        }

        this.open = true;
        this.title = "复制新增班级信息";
      });
    },
    handleSchedule(row) {
      // 自动排课
      this.loading = true
      this.loadingText = '后台正在自动排课, 请稍候……'
      const classId = row.classId || this.ids
      handleAutoSchedule(classId).then(response => {
        this.loading = false
        this.loadingText = ''
        //this.form = response.data;
      });
    },
    handleManulSchedule(row) {
      // 手动排课
      this.reset();
      const classId = row.classId || this.ids
      getClassInfo(classId).then(response => {
        this.form = response.data;

        let classTimeFlag = false
        if(this.form.eduClassTimeList && null !== this.form.eduClassTimeList) {
          // 班级上课时间有数据，即可
          classTimeFlag = true
        } else {
          this.msgError("请设置班级上课时间再排课");
        }

        let classSubjectFlag = false
        if(this.form.eduClassSubjectsList && null !== this.form.eduClassSubjectsList) {
          // 要有教学计划
          if(this.form.eduClassSubjectsList[0].teachPlanId && null !== this.form.eduClassSubjectsList[0].teachPlanId) {
            // 有一条就行
            classSubjectFlag = true
          }
        } else {
          this.msgError("请设置教学计划再排课");
        }

        if(classTimeFlag && classSubjectFlag) {
          this.manulScheduleOpen = true
          // 打开日历，可以设置课程信息

        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const classId = row.classId || this.ids
      getClassInfo(classId).then(response => {
        this.form = response.data;

        // 设置班级上课时间
        if(this.form.eduClassTimeList && null !== this.form.eduClassTimeList) {
          let times = []
          this.form.eduClassTimeList.forEach(data => {
            data.id = null
            times.push({weekDay: data.weekDay, scheduleSegment: data.scheduleSegment})
          })
          this.currentClassTime = JSON.parse(JSON.stringify(times))
          this.form.eduClassTimeList = JSON.parse(JSON.stringify(times)) // 重新初始化对象，避免直接保存ID冲突
        }

        // 班级科目信息设置
        this.classSubjects = []//.splice(0,1) // 删除原来的空行
        this.form.eduClassSubjectsList.forEach(subject => {
          this.classSubjects.push({ 
                subjectId: subject.subjectId,
                teacherDeptId: null,
                teachUserId: subject.teachUserId,
                teachPlanId: subject.teachPlanId,
                roomId: subject.roomId
          })
        })

        // 可选班型初始化
        if(this.checkedClassModel.length === 0) {
          this.form.eduClassClassModelList.forEach(model => {
            this.modelOptions.forEach(option => {
              if(''+model.modelId === ''+option.modelId) {
                this.checkedClassModel.push(option.modelId)
              }
            })
          })

          this.handleClassModelChange(this.checkedClassModel)
        }

        // 可选年级
        if(this.gradeOptions.length === 0) {
          this.gradeLength = 2
          this.form.eduClassGradeList.forEach(grade => {
            this.gradeOptions.push(grade.year)
            if(this.gradeLength < 12) {
              this.gradeLength += 2
            }
          })
        }

        // 可选校区
        if(this.checkCampusIds.length === 0) {
          this.form.eduClassCampusList.forEach(campus => {
            this.checkCampusIds.push(campus.campusId)
          })
        }
        // 排课规则
        if(this.scheduleRoleIds.length === 0) {
          this.form.eduClassScheduleRolesList.forEach(role => {
            this.scheduleRoleIds.push(role.roleValue.toString())
          })
        }

        this.open = true;
        this.title = "修改班级信息";
      });
    },
    handleSchedule(row) {
      
    },
    /** 提交按钮 */
    submitForm() {
      //console.log(JSON.stringify(this.checkCampusIds))
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 1 计算总科目数、总上课次数 -- 保存时再算一遍，前面切换到first可用，但有人会直接点保存
          this.form.subjectNum = 0
          this.form.subjectDays = 0
          // 计算总科目数和上课天数
          let v_teachPlanIds = []
          this.classSubjects.forEach(subject => {
            v_teachPlanIds.push(subject.teachPlanId)

            if(subject.subjectId) {
              this.form.subjectNum += 1
            }
          })

          // 重新获取教学计划列表 -- 后台去算好了
          /*
          if(v_teachPlanIds.length > 0) {
            listTeachPlanByIds(v_teachPlanIds).then(response => {
              this.teachPlanOptions = JSON.parse(JSON.stringify(response.data))
            })
            
            this.teachPlanOptions.forEach(data => {
              this.form.subjectDays  += data.teachPlanDays 
            })
            
          }
        */

          // 2 组装班级扩展数据，后台先删后插
          this.form.eduClassGradeList = []
          this.gradeOptions.forEach(option =>{
            this.form.eduClassGradeList.push({classId: this.form.classId, year: parseInt(option)})
          })
          this.form.eduClassClassModelList = []
          this.checkedClassModel.forEach(option =>{
            this.form.eduClassClassModelList.push({classId: this.form.classId, modelId: parseInt(option)})
          })
          this.form.eduClassCampusList = []
          this.checkCampusIds.forEach(option =>{
            this.form.eduClassCampusList.push({classId: this.form.classId, campusId: parseInt(option)})
          })
          this.form.eduClassSubjectsList = []
          this.classSubjects.forEach(option =>{
            if(option.subjectId) {
              this.form.eduClassSubjectsList.push({classId: this.form.classId, subjectId: option.subjectId,
                teachUserId: option.teachUserId, teachPlanId: option.teachPlanId, roomId : option.roomId})
            }
          })
          this.form.eduClassScheduleRolesList = []
          this.scheduleRoleIds.forEach(option =>{
            this.form.eduClassScheduleRolesList.push({classId: this.form.classId, roleValue: parseInt(option)})
          })
          
          //console.log(this.form.classTerm)
          if(!checkDigits(this.form.classTerm)) {
            if (this.form.classId != null) {
              updateClassInfo(this.form).then(response => {
                //console.log(response)
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addClassInfo(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            this.msgError("行课学期请填写一位整数");
          }
        }
      });
    },
    /** 班级状态确认 */
    submitClassStatus(row) {
      const classIds = row.classId || this.ids;
      const classStatus = this.selectStatusForm.classStatus;
      this.$confirm('是否确认更改班级信息为"' + classIds + '"的开班状态?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeClassStatus(classIds, classStatus);
        }).then(() => {
          this.msgSuccess("更改成功");
          this.selectStatusOpen = false;
          this.getList();
        })
    },
    /** 班级状态取消 */
    cancelClassStatus() {
      this.selectStatusOpen = false
      this.selectStatusForm.classStatus = null
    },
    /** 保存按钮 */
    submitHoldForm() {
      //console.log(JSON.stringify(this.checkCampusIds))
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 1 计算总科目数、总上课次数 -- 保存时再算一遍，前面切换到first可用，但有人会直接点保存
          this.form.subjectNum = 0
          this.form.subjectDays = 0
          // 计算总科目数和上课天数
          let v_teachPlanIds = []
          this.classSubjects.forEach(subject => {
            v_teachPlanIds.push(subject.teachPlanId)

            if(subject.subjectId) {
              this.form.subjectNum += 1
            }
          })

          // 重新获取教学计划列表 -- 后台去算好了
          /*
          if(v_teachPlanIds.length > 0) {
            listTeachPlanByIds(v_teachPlanIds).then(response => {
              this.teachPlanOptions = JSON.parse(JSON.stringify(response.data))
            })
            
            this.teachPlanOptions.forEach(data => {
              this.form.subjectDays  += data.teachPlanDays 
            })
            
          }
        */

          // 2 组装班级扩展数据，后台先删后插
          this.form.eduClassGradeList = []
          this.gradeOptions.forEach(option =>{
            this.form.eduClassGradeList.push({classId: this.form.classId, year: parseInt(option)})
          })
          this.form.eduClassClassModelList = []
          this.checkedClassModel.forEach(option =>{
            this.form.eduClassClassModelList.push({classId: this.form.classId, modelId: parseInt(option)})
          })
          this.form.eduClassCampusList = []
          this.checkCampusIds.forEach(option =>{
            this.form.eduClassCampusList.push({classId: this.form.classId, campusId: parseInt(option)})
          })
          this.form.eduClassSubjectsList = []
          this.classSubjects.forEach(option =>{
            if(option.subjectId) {
              this.form.eduClassSubjectsList.push({classId: this.form.classId, subjectId: option.subjectId,
                teachUserId: option.teachUserId, teachPlanId: option.teachPlanId, roomId : option.roomId})
            }
          })
          this.form.eduClassScheduleRolesList = []
          this.scheduleRoleIds.forEach(option =>{
            this.form.eduClassScheduleRolesList.push({classId: this.form.classId, roleValue: parseInt(option)})
          })
          
          //console.log(this.form.classTerm)
          if(!checkDigits(this.form.classTerm)) {
            if (this.form.classId != null) {
              updateClassInfo(this.form).then(response => {
                //console.log(response)
                this.msgSuccess("修改成功");
                this.getList();
              });
            } else {
              addClassInfo(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.getList();
              });
            }
          } else {
            this.msgError("行课学期请填写一位整数");
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const classIds = row.classId || this.ids;
      this.$confirm('是否确认删除班级信息编号为"' + classIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delClassInfo(classIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 撤销按钮操作 */
    handleCancel(row) {
      const classIds = row.classId || this.ids;
      this.$confirm('是否确认撤销班级信息编号为"' + classIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return cancelClassInfo(classIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("撤销成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有班级信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportClassInfo(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleTabChange() {
      if("first" === this.activeName) {
        this.form.subjectNum = 0
        this.form.subjectDays = 0
        // 计算总科目数和上课天数
        let v_teachPlanIds = []
        this.classSubjects.forEach(subject => {
           v_teachPlanIds.push(subject.teachPlanId)

          if(subject.subjectId) {
            this.form.subjectNum += 1
          }
        })

        // 重新获取教学计划列表
        if(v_teachPlanIds.length > 0) {
          listTeachPlanByIds(v_teachPlanIds).then(response => {
            this.teachPlanOptions = JSON.parse(JSON.stringify(response.data))
          })
          
          this.teachPlanOptions.forEach(data => {
            this.form.subjectDays = this.form.subjectDays + parseInt( data.teachPlanDays )
          })
        }
      } else if("second" === this.activeName) {
        if(this.checkedClassModel.length === 0) {
          //console.log( JSON.stringify(this.modelOptions))
          this.form.eduClassClassModelList.forEach(model => {
            this.modelOptions.forEach(option => {
              if(''+model.modelId === ''+option.modelId) {
                this.checkedClassModel.push(option.modelId)
              }
            })
          })

          this.handleClassModelChange(this.checkedClassModel)
        }
      } else if("third" === this.activeName) {
        if(this.gradeOptions.length === 0) {
          this.gradeLength = 2
          this.form.eduClassGradeList.forEach(grade => {
            this.gradeOptions.push(grade.year)
            if(this.gradeLength < 12) {
              this.gradeLength += 2
            }
          })
        }
      } else if("fourth" === this.activeName) {
        if(this.checkCampusIds.length === 0) {
          this.form.eduClassCampusList.forEach(campus => {
            this.checkCampusIds.push(campus.campusId)
          })
        }
      } else if("sixth" === this.activeName) {
        if(this.scheduleRoleIds.length === 0) {
          this.form.eduClassScheduleRolesList.forEach(role => {
            this.scheduleRoleIds.push(role.roleValue.toString())
          })
        }
      }

      // 这个要独立处理，可能有已添加但未保存的情况  来回切换
      if("fivth" === this.activeName) {
        if(this.form.eduClassSubjectsList.length > 0) {
          this.classSubjects = []//.splice(0,1) // 删除原来的空行
          // 因为教师 & 教学计划  俩列表是动态获取的，因此此处要封装列表，否则显示不正确
          let v_teachUserIds = []
          let v_teachPlanIds = []
          this.form.eduClassSubjectsList.forEach(subject => {
            v_teachUserIds.push(subject.teachUserId)
            v_teachPlanIds.push(subject.teachPlanId)
            
            this.classSubjects.push(
              { 
                subjectId: subject.subjectId,
                teacherDeptId: null,
                teachUserId: subject.teachUserId,
                teachPlanId: subject.teachPlanId,
                roomId: subject.roomId
              })
          })

          if(v_teachUserIds.length > 0) {
            listUserByByIds(v_teachUserIds).then(response => {
              this.teacherUserOptions = response.data
            })
          }
          if(v_teachPlanIds.length > 0) {
            listTeachPlanByIds(v_teachPlanIds).then(response => {
              this.teachPlanOptions = JSON.parse(JSON.stringify(response.data))
            })
          }
        }
      } else {
        if(this.classSubjects.length > 0) {
          this.form.eduClassSubjectsList = []
          this.classSubjects.forEach(option =>{
            if(option.subjectId) {
              this.form.eduClassSubjectsList.push({classId: this.form.classId, subjectId: option.subjectId,
                teachUserId: option.teachUserId, teachPlanId: option.teachPlanId, roomId : option.roomId})
            }
          })
        }
      }
    },
    //--------------------------- 选项卡功能
    handleClassModelCheckAllChange(val) {
      if(!val) {
        this.checkedClassModel = []
        //this.checkClassModelAll = false
      } else {
        this.modelOptions.forEach(option => {
          this.checkedClassModel.push(option.modelId)
        })
        //this.checkClassModelAll = true
      }
      this.isIndeterminateClassModel = false;
    },
    handleClassModelChange(value) {
      let checkedCount = value.length;
      this.checkClassModelAll = checkedCount === this.modelOptions.length;
      this.isIndeterminateClassModel = checkedCount > 0 && checkedCount < this.modelOptions.length;
    },
    checkGrades(val) {
      let v_exists = true
      this.gradeOptions.forEach(grade => {
        if(grade === val) {
          v_exists = false
        }
      })

      if(v_exists) {
        this.gradeOptions.push(val)
        if(this.gradeLength < 12) {
          this.gradeLength += 2
        }
      }
    },
    handleClose(tag) {
      this.gradeOptions.splice(this.gradeOptions.indexOf(tag), 1);
      if(this.gradeLength > 2 && this.gradeOptions.length < 5) {
        this.gradeLength -= 2
      }
    },
    closeOnSelect() {
      this.checkCampusIds = []
    },
    addClassSubjects() {
      //console.log(this.classSubjects.length)
      this.classSubjects.push({
        subjectId: null,
        teacherDeptId: null,
        teachUserId: null,
        teachPlanId: null,
        roomId: null
        })
    },
    delClassSubjects(index) {
      if(this.classSubjects.length > 1) {
        this.classSubjects.splice(index,1)
      } else {
        this.msgError("至少有一个科目");
      }
    },
    queryRoomAsync(queryString, cb) {
      if(this.form.campusId === undefined || this.form.campusId === null) {
        this.$message({
            type: 'warning',
            message: '请选择校区'
          })
          return
      }

      let param = {
        roomName: queryString,
        campusId: this.form.campusId,
      }
      listAllRooms(param).then(response => {
          this.roomOptions = response.data
        })
    },
    getReturnData(data) {
      this.form.eduClassTimeList = []
      // 获取设置的上课信息
      //console.log('return-data', JSON.stringify(data))
      for(let x=0; x<data.length; x++) {
        for(let y=0; y<data[x].length; y++) {
          if(data[x][y].class === 'ui-selected') {
            this.form.eduClassTimeList.push({weekDay: x+1, scheduleSegment: y})
          }
        }
      }
      //console.log('geshihua ', JSON.stringify(this.form.eduClassTimeList))
    },
    // *************************** 手动排课日历组件
    eventLimiTtext(data) {
      return `查看剩余的${data}条`
    },
    /**
     * 格式化日列表左侧的时间
     */
    listDayFormat(data) {
      const timestamp = new Date(data.date.marker).getTime()
      const dateTime = moment(timestamp).format('ll')
      const week = moment(timestamp).format('dddd').replace('星期', '周')
      const dataValue = week + '  ' + dateTime
      return dataValue
    },
    /**
     * 点击事件
     */
    eventClick(data) {
      if (data.event.extendedProps && data.event.extendedProps.typeId == -2) {
        this.relationID = data.event.id
        this.relationCrmType = 'task'
        setTimeout(() => {
          this.showFullDetail = true
        }, 200)
        return
      }
      this.eventId = data.event.id
      this.todayDetailData = {
        startTime: data.event.start || '',
        endTime: data.event.end || data.event.start,
        id: data.event.id,
        title: data.event.title,
        userId: this.activeTime.userId,
        groupId: data.event.groupId,
        backgroundColor: data.event.backgroundColor
      }
      // 不是组件自带的字段都会被插入到entendedProps里面
      if (data.event.extendedProps) {
        this.todayDetailData.name = data.event.extendedProps.name
        this.todayDetailData.createTime = data.event.extendedProps.createTime
        this.todayDetailData.headTitle = data.event.title
        this.todayDetailData.crmType = data.event.extendedProps.crmType
        this.todayDetailData.typeId = data.event.extendedProps.typeId || 3
      }
      this.showTodayDetail = true
    },
    /**
     *  日期渲染时，触发的事件，默认传入info,一个包含view和el的对象
     */
    datesRender(info) {
      // 只有单日列表无数据时，才创建img
      if (info.view.type === 'listDay') {
        if (info.el.textContent === '暂无日程') {
          const img = document.createElement('img')
          // 写id保证只创建一次
          img.id = 'emityImg'
          img.src = require('@/assets/img/empty.png')
          // 保证一定是暂无日程而不是有些事件叫做暂无日程
          const div = document.getElementsByClassName('fc-list-empty-wrap1')[0]
          if (div) {
            div.insertBefore(img, div.children[0])
          }
        }
      } else if (info.view.type === 'dayGridMonth') {
        if (this.currentTime === info.view.title) {
          if (this.selectDiv && document.querySelector(`td[data-date="${this.selectDiv}"]`)) {
          // 保证切换模式时，关联的日期被选中
            document.querySelector(`td[data-date="${this.selectDiv}"]`).classList.add('select-day')
          }
        } else {
          // this.$refs.schedule.selectMouth(info.view.activeStart)
          this.currentTime = info.view.title
        }
        if (this.activeTime.startTime !== new Date(info.view.activeStart).getTime()) {
          this.activeTime.startTime = new Date(info.view.activeStart).getTime()
          this.activeTime.endTime = new Date(info.view.activeEnd).getTime()
          // 优化 只有月切换才会刷新列表
          const leadTime = this.activeTime.endTime - this.activeTime.startTime
          if (leadTime > 24 * 60 * 60 * 1000) {
            //this.getCusCheck()
          }
        }
      } else if (info.view.type === 'timeGridWeek') {
        // 周逻辑处理
      }
      this.listDataType = info.view.type
    },
      /**
     * 周点击
     */
    toggleWeekends() {
      this.calendarWeekends = !this.calendarWeekends // update a property
    },
    /**
     * 天点击
     */
    handleDateClick(arg) {
      console.log(1111)
      if (this.selectDiv === arg.dateStr) {
        this.showCreate = true
      } else {
        this.selectDiv = arg.dateStr
        // 注开会生成提示文字
        // const div = document.createElement('div')
        // div.style.position = 'absolute'
        // div.style.left = arg.jsEvent.clientX + 20 + 'px'
        // div.style.top = arg.jsEvent.clientY - 20 + 'px'
        // div.style.border = '1px solid #999'
        // div.style.backgroundColor = '#999'
        // div.style.padding = '10px'
        // div.style.fontSize = '12px'
        // div.style.zIndex = getMaxIndex()
        // div.style.boxShadow = ''
        // div.innerHTML = '双击新建'
        // div.style.color = '#333'
        // div.className = 'create__event?'
        // if (document.getElementsByClassName('create__event?')[0]) {
        //   const oldDiv = document.getElementsByClassName('create__event?')[0]
        //   document.documentElement.removeChild(oldDiv)
        // }
        // document.documentElement.appendChild(div)
        // console.log(arg, 'arg')
      }
      const td = document.getElementsByClassName('select-day')
      if (td && td.length) {
        td[0].classList.remove('select-day')
      }
      arg.dayEl.classList.add('select-day')
      // if (arg.dateStr) {
      //   this.$refs.schedule.selectDay(arg.dateStr, true)
      // }
    },
  }
};
</script>
<style lang="scss" scoped>
@import './style/color.scss';
@import './style/fullCalendar.scss';
  .demonstration {
    line-height: 30px;
  }

  .zZindex {
    z-index:9999 !important;
  }

  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px;

      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }

      .highlighted .addr {
        color: #ddd;
      }
    }
  }

  .box-right{
    background-color: #fff;
    height: 600px;
    width: 100%;
    overflow: hidden;
    border:1px solid #f3f3f3;
    padding: 10px 0px 0px;
  }
</style>